package hotel.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hotel.entity.Authority;
import hotel.service.IAuthorityService;
import util.JSONUtil;

@Controller
public class AuthorityController {
	// Jackson
	private final static ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private IAuthorityService<Authority> authorityService;

	@ResponseBody
	@RequestMapping(value = "authoritylist")
	public String getAuthorityList(Model model) {
		//设置将日期转换成JSON的格式
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		String json = null;
		try {
			json = mapper.writeValueAsString(authorityService.listAll("Authority"));
			json = "{\"data\":" + json + "}";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value="authorityManagement")
	public String authorityManagement() {
		
		return "authority/authoritylist";
	}
	
	@RequestMapping(value = "addAuthority", method = RequestMethod.GET)
	public String add() {
		return "authority/add";
	}

	@ResponseBody
	@RequestMapping(value = "addAuthority", method = RequestMethod.POST)
	public String addAuthority(Authority authority) {
		Date date=new Date();
		authority.setAddTime(date);
		authority.setEditTime(date);
		if (authorityService.save(authority))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}

	@RequestMapping(value = "editAuthority", method = RequestMethod.GET)
	public String edit(int authorityid, Model model) {
		model.addAttribute("authority", authorityService.findById(Authority.class, authorityid));
		return "authority/edit";
	}

	@ResponseBody
	@RequestMapping(value = "editAuthority", method = RequestMethod.POST)
	public String editAuthority(Authority authority) {
		authority.setEditTime(new Date());
		if (authorityService.update(authority))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}

	@ResponseBody
	@RequestMapping(value = "deleteAuthority")
	public String deleteAuthority(int authorityid) {
		if (authorityService.deleteById("Authority", authorityid))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
}
